package lgkj.meicqt20.view;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.VideoView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import lgkj.meicqt20.bean.AdverBean;
import lgkj.meicqt20.bean.MessageEvent;
import lgkj.meicqt20.utils.DbController;
import lgkj.meicqt20.utils.SharedPreferencesUtils;
import lgkj.meicqt20.utils.VideoDownLoadUtil;


/**
 * Created by hjx on 2017/5/13.
 */

public class BannerVideoView extends VideoView {
    private String TAG = "BannerVideoView";
    private Context mContext;


    private int mCurPlay;
    private boolean isPlay;
    private DbController dbController;


    public int getmCurPlay() {
        Log.w(TAG, "BannerVideoView: " + mCurPlay);
        if (mCurPlay > 0 && mCurPlay < adverBeans.size())
            return mCurPlay;
        return 0;
    }

    private List<AdverBean> adverBeans;
    private List<String> loadVideoUrl = new ArrayList<>();
    SharedPreferencesUtils sharePreferenceUtil;


    public void setLevel(boolean level) {
        isLevel = level;
    }

    private boolean isLevel = true;

    public BannerVideoView(Context context) {
        this(context, null);
    }

    public BannerVideoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        sharePreferenceUtil = new SharedPreferencesUtils(context);
        Log.d(TAG, "BannerVideoView: " + sharePreferenceUtil.getDataList("loadVideoUrl").toString());
        dbController = new DbController(context);
        adverBeans = dbController.searchAll();
        init(context);
        initEvent();
    }

    private void initEvent() {
        setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                try {
                    isPlay = false;
                    mediaPlayer.reset();
                    Log.i(TAG, "setOnErrorListener: " + isPlay);
//                    Toast.makeText(mContext, "由于网络问题，" + StartPageActivity.listBean.get(i).getAd_text() + "下载失败，下次启动重新下载！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    Log.e(TAG, "onError: " + e.getMessage());
                } finally {
                    play();
                }
                return true;
            }
        });
        setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                try {
                    isPlay = false;
                    Log.i(TAG, "Completion: " + isPlay);
                } catch (Exception e) {
                    Log.e(TAG, "onError: " + e.getMessage());
                } finally {
                    MessageEvent messageEvent = new MessageEvent();
                    if (mCurPlay >= adverBeans.size()) {
                        mCurPlay = 0;
                    }
                    String url = adverBeans.get(mCurPlay).getAd_cover();
                    Log.i(TAG, "onCompletion: " + url + ",mCurPlay:" + mCurPlay + ",toString:" + adverBeans.get(mCurPlay).toString());
                    messageEvent.setMessage(mCurPlay + "");
                    messageEvent.setTagName("completionListener");
                    EventBus.getDefault().post(messageEvent);
                    play();
                }
            }
        });
    }

//    public interface videoCompletion {
//        void Completion(int postion);
//    }

    private void init(Context context) {
        mCurPlay = 0;
        isLevel = true;
        this.mContext = context;
//        loadVideoUrl = sharePreferenceUtil.getDataList("loadVideoUrl");
        Log.d(TAG, "init: " + adverBeans.size());
//        if (adverBeans.size() < VideoDownLoadUtil.filePaths().size()) {
//            adverBeans = VideoDownLoadUtil.filePaths();
//        }
//        Log.d(TAG, "loadVideoUrl.size():" + loadVideoUrl.size());
    }

    public void play() {
        try {
            Log.i(TAG, "play: " + isPlay + ",mCurPlay" + mCurPlay);
            if (isPlay) {
                return;
            }
            if (adverBeans.size() <= 0) {
                return;
            }
            if (mCurPlay >= adverBeans.size()) {
                mCurPlay = 0;
                Log.i(TAG, "play: 播放完一轮广告" + mCurPlay);

            }
            String name = VideoDownLoadUtil.getVideoFullName(adverBeans.get(mCurPlay).getAd_file());
            String path = VideoDownLoadUtil.mRootPath + name;
            if (mCurPlay == 0) {
                decideVideoLock();
            }
            old_duration = -1;
            isPlay = true;
            File f = new File(path);
            Log.w(TAG, "播放第" + mCurPlay + "个广告:" + ",视频地址：" + path + ",exists:" + !f.exists());
            if (f.exists()) {
                setVideoURI(Uri.parse(path));
                start();
            }
//            ((FirstActivity) mContext).vp_ban.setVisibility(GONE);
            Log.i(TAG, "play: ");
            if (isLevel)
                mCurPlay++;
        } catch (Exception e) {
            Log.e(TAG, "play: " + e.getMessage());
        }

    }


    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (hasWindowFocus) {
            start();
        } else {
            pause();
        }
        super.onWindowFocusChanged(hasWindowFocus);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    long old_duration = -1;//记录上一次的播放时间，不用置零（感觉）
    private final Handler mHandlerLock = new Handler();
    private Runnable mRunLock = new Runnable() {
        public void run() {
            Log.i(TAG, "run: isPlaying():" + isPlaying());
            long duration = getCurrentPosition();
            Log.i(TAG, "run: duration:" + duration + "old_duration" + old_duration);
            if (old_duration == duration && (!isPlaying())) {
                Log.e(TAG, "run: 视频暂停:" + isLevel);
                isPlay = false;
                if (isLevel)
                    play();
            }
            old_duration = duration;
            mHandlerLock.postDelayed(mRunLock, 3 * 1000);//3秒进行一次判断
        }
    };

    private void decideVideoLock() {
        mHandlerLock.removeCallbacks(mRunLock);
        mHandlerLock.postDelayed(mRunLock, 0);
    }

}
